﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Southern.Common.Utilities;
using Southern.Models.Southern;
using Southern.Models.Southern.Base;

namespace Southern.Controllers
{
    public class AccountController : AdminBaseController
    {
        //
        // GET: /Account/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LoginModel loginModel)
        {
            if (ModelState.IsValid)
            {
                bool encrypted = true;
                string pass = encrypted ? loginModel.Password : SecurityUtility.MD5Encrypt(loginModel.Password);
                var isValid = Services.Get<IUserRepository>().UserIsValid(loginModel.UserName, pass);
                if (isValid)
                {
                    FormsAuthentication.RedirectFromLoginPage(loginModel.UserName, false);
                    return RedirectToAction("Index", "Home", new { area = "Admin" });
                }
                else
                {
                    ModelState.AddModelError("", "Invalid username or password");
                    return View("Index");
                }
            }
            return View();
        }

        [HttpGet]
        public ActionResult LogOn(string returnUrl)
        {
            if (true)// if user is authenticate
            {
                FormsAuthentication.RedirectFromLoginPage(CurrentUser.Username, false);
                return null;
            }
            else
            {
                return View(new LoginModel() { ReturnUrl = returnUrl });
            }
        }
    }

    public class LoginModel
    {
        [Required]
        public string UserName { get; set; }

        [Required]
        public string Password { get; set; }

        public bool RememberMe { get; set; }

        public string ReturnUrl { get; set; }
    }
}
